# 1.导包
import time
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By

# 2.打开浏览器（创建浏览器驱动对象）
service = Service(r'F:\python 3.12\chromedriver.exe')  # 你的chromedriver路径
driver = webdriver.Chrome(service=service)
driver.maximize_window()  # 最大化窗口，方便操作

# 3.访问淘宝首页
driver.get("https://www.taobao.com")
time.sleep(2)  # 等待页面加载

# 4.添加你的Cookie（使用你提供的Cookie信息，已按域名匹配整理）
cookies_to_add = [
    # cookie1 对应各域名
    {"name": "cookie1", "value": "BxzCXz8g2YU3K2EqzR1UVdVv4jaESoxqp9COWSweYuE%3D", "domain": ".tmall.com"},
    {"name": "cookie1", "value": "BxzCXz8g2YU3K2EqzR1UVdVv4jaESoxqp9COWSweYuE%3D", "domain": ".taobao.com"},
    {"name": "cookie1", "value": "BxzCXz8g2YU3K2EqzR1UVdVv4jaESoxqp9COWSweYuE%3D", "domain": ".tmall.hk"},
    {"name": "cookie1", "value": "BxzCXz8g2YU3K2EqzR1UVdVv4jaESoxqp9COWSweYuE%3D", "domain": ".fliggy.com"},

    # cookie17 对应各域名
    {"name": "cookie17", "value": "UUUGrdCRe18xFwv3D%3D%3D", "domain": ".tmall.hk"},
    {"name": "cookie17", "value": "UUUGrdCRe18xFwv3D%3D%3D", "domain": ".taobao.com"},
    {"name": "cookie17", "value": "UUUGrdCRe18xFwv3D%3D%3D", "domain": ".tmall.com"},
    {"name": "cookie17", "value": "UUUGrdCRe18xFwv3D%3D%3D", "domain": ".fliggy.com"},

    # cookie2 对应各域名
    {"name": "cookie2", "value": "128f6ace785fa39c4734dc1f731889dd", "domain": ".tmall.hk"},
    {"name": "cookie2", "value": "128f6ace785fa39c4734dc1f731889dd", "domain": ".tmall.com"},
    {"name": "cookie2", "value": "128f6ace785fa39c4734dc1f731889dd", "domain": ".fliggy.com"},
    {"name": "cookie2", "value": "128f6ace785fa39c4734dc1f731889dd", "domain": ".taobao.com"}
]

# 5.逐个添加Cookie并捕获异常
for cookie in cookies_to_add:
    try:
        driver.add_cookie(cookie)
        print(f"成功添加：{cookie['name']}（{cookie['domain']}）")
    except Exception as e:
        print(f"添加失败 {cookie['name']}：{str(e)}")

# 6.刷新页面使Cookie生效
driver.refresh()
time.sleep(3)  # 等待刷新后加载

# 7.验证登录状态（可手动点击"我的淘宝"查看，或代码自动检查）
try:
    # 尝试定位"我的淘宝"按钮（登录后可见）
    my_taobao = driver.find_element(By.LINK_TEXT, "我的淘宝")
    print("登录成功！已定位到'我的淘宝'")
except:
    print("登录可能失败，请手动检查")

# 8.停留10秒观察效果
time.sleep(60)

# 9.关闭浏览器
driver.quit()